const fs = require('fs');
const { isAbsolute, join } = require('path');
const request = require('request-promise');

/**
 * @param { string } uri
 */
async function retrieveFile(uri) {
  uri = uri.startsWith('http') || isAbsolute(uri) ? uri : join(process.cwd(), uri);
  if (fs.existsSync(uri)) {
    return uri.endsWith('json') ? require(uri) : fs.readFileSync(uri).toString();
  }

  console.log("uri", uri, "json",  uri.endsWith('json'))

  try {
    return await request({ uri, json: uri.endsWith('json'),timeout: 30000, headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'} });
  } catch (error) {
    console.error(`failed to download the file from ${uri}`);
    process.exit(1);
  }
}

module.exports = {
  retrieveFile,
};
